package com.foo.designpattern.flyweight.ComplexFlyweight;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * com.foo.designpattern.flyweight.ComplexFlyweight
 * Created with IntelliJ IDEA.
 * Created by jiang on 2016-05-24 10:02.
 *
 * @Description 享元工厂(FlyweightFactory)角色
 * 享元工厂角色：负责创建和管理享元角色，本角色必须保证享元对象可以被系统适当地共享。
 * 享元工厂角色提供两种不同的方法：一种用于提供单纯享元对象，另一种用于提供复合享元对象。
 */

public class FlyweightFactory {
    private Map<Character, Flyweight> files = new HashMap<Character, Flyweight>();

    /**
     * 复合享元工厂方法
     *
     * @param compositeState
     * @return
     */
    public Flyweight factory(List<Character> compositeState) {
        ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
        for (Character state : compositeState) {
            compositeFly.add(state, this.factory(state));
        }
        return compositeFly;
    }

    public Flyweight factory(Character state) {
        // 先从缓存中查找对象
        Flyweight fly = files.get(state);
        if (null == fly) {
            // 如果对象不存在则创建一个新的Flyweight对象
            fly = new ConcreteFlyweight(state);
            // 把扎个新的flyweight对象添加到缓存中
            files.put(state, fly);
        }
        return fly;
    }

}
